<template>
  <el-dialog
    v-model="visible"
    title="选择区域"
    :modal="false"
    :close-on-click-modal="false"
    style="width: 30%;"
  >
    <div>
      <el-input
        v-model="areaName"
        clearable
        class="area-search-input"
        placeholder="区域关键词"
      />
      <el-tree
        ref="tree2Ref"
        :data="areaTreeData"
        node-key="areaId"
        :filter-node-method="filterNode"
        :props="props"
        :expand-on-click-node="true"
        :default-checked-keys="defaultCheckedKeys"
        show-checkbox
      />
    </div>

    <template #footer>
      <span>
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitProds()"
        >确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
const areaName = ref('')
const emit = defineEmits(['refreshSelectArea'])
const props = {
  id: 'areaId',
  label: 'areaName',
  children: 'children'
}

const defaultCheckedKeys = ref([]) // 默认选中的节点key
const tree2Ref = ref(null)
watch(
  () => areaName.value,
  (val) => {
    tree2Ref.value?.filter(val)
  }
)

const filterNode = (value, data) => {
  if (!value) return true
  return data.areaName.indexOf(value) !== -1
}

// eslint-disable-next-line no-unused-vars
const visible = ref(false)

onMounted(() => {
  getDataList(page)
})

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 100 // 每页显示多少条
})
const areaTreeData = ref(null)
const getDataList = (pageParam, params) => {
  http({
    url: http.adornUrl('admin/area/list'),
    method: 'get',
    params: http.adornParams(Object.assign({
      current: pageParam == null ? page.currentPage : pageParam.currentPage,
      size: pageParam == null ? page.pageSize : pageParam.pageSize
    }, params))
  }).then(({ data }) => {
    areaTreeData.value = treeDataTranslate(data, 'areaId', 'parentId')
  })
}

/**
 * 获取数据列表
 */
const init = (selectAreaParam) => {
  visible.value = true
  defaultCheckedKeys.value = selectAreaParam
}

defineExpose({ init })

/**
 * 确定事件
 */
const submitProds = () => {
  const _items = []

  for (const _item of tree2Ref.value.getCheckedNodes()) {
    if (!_item.children) {
      _items.push(_item)
    }
  }

  if (!_items.length) {
    ElMessage({
      message: '请选择区域',
      type: 'error',
      duration: 1000,
      onClose: () => {}
    })
    return
  }

  emit('refreshSelectArea', _items)
  tree2Ref.value.setCheckedKeys([])
  visible.value = false
}
</script>

<style lang="scss" scoped>
.area-search-input {
  width: 100%;
  margin-bottom: 8px;
}

:deep(.el-tree-node) .addr-name {
  width: 100%;
}
</style>
